package com.chinasofti.method;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo3 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //method1();
        //method2();
        //method3();
        Class clazz = Class.forName("com.chinasofti.ref.method.Student");
        //获取私有构造器
        Constructor constructor = clazz.getDeclaredConstructor(String.class);
        //private修饰的成员不能直接使用
        //如果反射要强行使用，需要临时取消访问限制
        constructor.setAccessible(true);

        Student student = (Student) constructor.newInstance("zhagsan");
        System.out.println("student = " + student);
    }

    private static void method3() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class clazz = Class.forName("com.chinasofti.ref.method.Student");
        Student student = (Student) clazz.newInstance();//了解
        System.out.println(student);
    }

    //@Deprecated
    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Class.forName("com.chinasofti.ref.method.Student");
        Constructor constructor = clazz.getConstructor();
        Student student = (Student) constructor.newInstance();
        System.out.println("student = " + student);
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //获取class对象
        Class clazz = Class.forName("com.chinasofti.ref.method.Student");
        //获取Constructor对象
        Constructor constructor = clazz.getConstructor(String.class,int.class);

        Student student = (Student)constructor.newInstance("张三",23);
        System.out.println(student);
    }

}